﻿Imports ATS.UI.Process
Imports ATS.Business.Entities
Imports System.ComponentModel
Imports System.ServiceModel
Imports System.Collections.Specialized
Imports System.Threading
Imports System.Collections.ObjectModel

Public Class DepartmentWindow
    Private WithEvents _backgroundWorker As BackgroundWorker
    Private WithEvents _backgroundWorker_Page_Load As BackgroundWorker
    Private WithEvents _backgroundWorker_Save As BackgroundWorker
    Private WithEvents _backgroundWorker_CheckExisting As BackgroundWorker
    Public WithEvents oWindowList As OpenedWindowList = OpenedWindowList.GetList()
    Private WithEvents oWindow As OpenedWindowClass
    Private _upc As SubmitterUserProcess = Nothing
    Private _departmentDetail As Department = Nothing
    Private _departmentDetail_asynch As Department = Nothing
    Public WithEvents _departmentList As ObservableCollection(Of Department)

#Region "Window Events"
    Private Sub DepartmentWindow_Closed(sender As Object, e As System.EventArgs) Handles Me.Closed
        Dim ied As IEnumerable(Of OpenedWindowClass) = From d In oWindowList Where d.WindowID = Me.Name
        oWindowList.Remove(ied.First)
        If Application.Current.Windows.Count = 1 Then
            Application.Current.Windows(0).Activate()
        End If
    End Sub
    Private Sub DepartmentWindow_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles Me.Closing
        If Not _departmentDetail Is Nothing Then
            If _departmentDetail.IsDirty Then
                If _
                    MessageBox.Show("There are unsaved entries. Do you really want to exit?", "Exit", _
                                     MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.No Then
                    e.Cancel = True
                    _departmentDetail.EndEdit()
                End If
            End If
        End If
    End Sub

    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        _upc = New SubmitterUserProcess()
    End Sub

    Private Sub DepartmentWindow_Loaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        _backgroundWorker_Page_Load = New BackgroundWorker
        _backgroundWorker_Page_Load.RunWorkerAsync()
    End Sub
#End Region

#Region "Control Events"
    Private Sub comboBoxDepartment_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
    End Sub

    Private Sub listBoxdepartments_SelectionChanged(sender As Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles listBoxDepartments.SelectionChanged
        If Not _departmentDetail Is Nothing Then
            If _departmentDetail.IsDirty Then
                If _
                    MessageBox.Show("Save entries before leaving?", "Save Data", MessageBoxButton.YesNo, _
                                     MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                    Savedepartment()
                Else
                    If Not _departmentDetail.DepartmentId = 0 Then
                        CancelEdit()
                    End If

                End If
            End If
        End If
        LoadSelectedDepartment()
    End Sub

    Private Sub ExpanderList_Expanded(sender As Object, e As System.Windows.RoutedEventArgs) Handles ExpanderList.Expanded
        busyAnimation.Visibility = Windows.Visibility.Visible
        If _departmentList Is Nothing Then
            _backgroundWorker = New BackgroundWorker
            _backgroundWorker.RunWorkerAsync()
        Else
            busyAnimation.Visibility = Windows.Visibility.Collapsed
        End If
    End Sub

    Private Sub searchBox_GotFocus(sender As Object, e As RoutedEventArgs) Handles searchBox.GotFocus
        If searchBox.Text.ToUpper.Contains("SEARCH") Then
            searchBox.Text = Nothing
        End If
    End Sub

    Private Sub searchBox_TextChanged(sender As Object, e As TextChangedEventArgs) Handles searchBox.TextChanged
        If Not listBoxdepartments Is Nothing Then
            Dim icview As ICollectionView = CollectionViewSource.GetDefaultView(listBoxDepartments.ItemsSource)
            icview.Filter = New Predicate(Of Object)(AddressOf FilterUserTable)
        End If
    End Sub

    Private Sub buttonNew_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles buttonNew.Click
        'ExpanderList.IsExpanded = True
        If Not _departmentDetail Is Nothing Then
            If _departmentDetail.IsDirty Then
                If _
                    MessageBox.Show("There are unsaved entries. Do you want to abandon your changes?", "Refresh", _
                                     MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                    _departmentDetail.ResetDirtyBit()
                    SetWindowProperties(_departmentDetail.IsDirty)
                    NewItemCanvas.Visibility = Windows.Visibility.Visible
                    ucNewItem.ucLabel = "New Category code"
                End If
            Else
                NewItemCanvas.Visibility = Windows.Visibility.Visible
                ucNewItem.ucLabel = "New Category code"
            End If
        Else
            NewItemCanvas.Visibility = Windows.Visibility.Visible
            ucNewItem.ucLabel = "New Category code"
        End If
    End Sub

    Private Sub buttonRefresh_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles buttonRefresh.Click
        If Not _departmentDetail Is Nothing Then
            If _departmentDetail.IsDirty Then
                If MessageBox.Show("There are unsaved entries. Do you really want to refresh the data?", "Refresh", _
                                     MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                    If _departmentDetail.DepartmentId = 0 Then
                        ClearAllControls()
                    Else
                        CancelEdit()
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub buttonSave_Click(sender As Object, e As RoutedEventArgs) Handles buttonSave.Click
        If Not _departmentDetail Is Nothing Then
            If _departmentDetail.IsDirty Then
                Savedepartment()
            End If
        End If
    End Sub
#End Region

#Region "Background Workers"
    ' This event handler is where the actual work is done.
    Private Sub _backgroundWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles _backgroundWorker.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        LoadDepartments()
    End Sub

    Private Sub _backgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles _backgroundWorker.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            listBoxDepartments.ItemsSource = _departmentList
            RefreshRecordCount()
            If _departmentList Is Nothing Then
                listBoxDepartments.SelectedIndex = -1
            End If
        End If
        busyAnimation.Visibility = Windows.Visibility.Collapsed
    End Sub

    Private Sub _backgroundWorker_SaveDoWork( _
                                          ByVal sender As Object, _
                                          ByVal e As DoWorkEventArgs) _
        Handles _backgroundWorker_Save.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

        If e.Argument = "edit" Then
            _departmentDetail_asynch = _upc.UpdateDepartmentDetails(_departmentDetail)
        ElseIf e.Argument = "new" Then
            _departmentDetail_asynch = _upc.CreateDepartment(_departmentDetail)
        End If
    End Sub

    Private Sub _backgroundWorker_SaveRunWorkerCompleted( _
                                                      ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
        Handles _backgroundWorker_Save.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            listBoxDepartments.ItemsSource = _departmentList
            busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Collapsed
            _departmentDetail = _departmentDetail_asynch
            _departmentDetail_asynch = Nothing
            _departmentDetail.ResetDirtyBit()
            SetWindowProperties(_departmentDetail.IsDirty)
        End If
    End Sub

    ' This event handler is where the actual work is done.
    Private Sub _backgroundWorker_Page_Load_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles _backgroundWorker_Page_Load.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
    End Sub

    Private Sub _backgroundWorker_Page_Load_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles _backgroundWorker_Page_Load.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        End If
    End Sub

    Private Sub _backgroundWorker_ChckExistingUserDoWork( _
                                         ByVal sender As Object, _
                                         ByVal e As DoWorkEventArgs) _
       Handles _backgroundWorker_CheckExisting.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        e.Result = _upc.GetDepartmentDetails(e.Argument)
    End Sub

    Private Sub _backgroundWorker_ChckExistingRunWorkerCompleted( _
                                                      ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
        Handles _backgroundWorker_CheckExisting.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            If Not e.Result Is Nothing Then
                ucNewItem.LabelError.Content = "Department code already exist."
            Else
                listBoxDepartments.SelectedIndex = -1
                _departmentDetail = New Department()
                _departmentDetail.DepartmentCode = ucNewItem.TextBoxNewUser.Text
                textboxCode.Text = ucNewItem.TextBoxNewUser.Text
                NewItemCanvas.Visibility = Windows.Visibility.Collapsed
                mainOverlay.Visibility = Visibility.Collapsed
                Me.Title = _departmentDetail.DepartmentCode
                SetWindowProperties(_departmentDetail.IsDirty)
                Me.DataContext = _departmentDetail
            End If
        End If
        ucNewItem.busyAnimationNewUser_visibility = Windows.Visibility.Collapsed
    End Sub
#End Region

#Region "Support Procedures"
    Private Sub CancelEdit()
        _departmentDetail.CancelEdit()
        _departmentDetail.ResetDirtyBit()
        SetWindowProperties(_departmentDetail.IsDirty)
    End Sub

    Private Sub LoadDepartments()
        Try
            If _departmentList Is Nothing Then
                _departmentList = New ObservableCollection(Of Department)(_upc.GetAllDepartments)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message & ControlChars.Lf & ex.ToString, "Error loading Department list", MessageBoxButton.OK, _
                             MessageBoxImage.[Error])
        End Try
    End Sub

    Private Sub RefreshRecordCount()
        If Not _departmentList Is Nothing Then
            If _departmentList.Count = 1 Then
                ExpanderText.Text = _departmentList.Count & " record found"
            Else
                ExpanderText.Text = _departmentList.Count & " records found"
            End If
        End If
    End Sub

    Private Sub SetWindowProperties(dirty As Boolean)
        If dirty Then
            Me.Title &= If(Not Me.Title.ToUpper.Contains("UNSAVED"), " (unsaved)", "")
        Else
            Me.Title = If(Title.ToUpper.Contains("UNSAVED"), Me.Title.Substring(0, Me.Title.Length - 10), Me.Title)
        End If

        For itemIndex = 0 To oWindowList.Count - 1
            If oWindowList(itemIndex).WindowID = Me.Name Then
                oWindowList(itemIndex).WindowName = Me.Title
                oWindowList(itemIndex).WindowIsDirty = dirty
            End If
        Next
    End Sub

    Private Sub SaveDepartment()
        busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Visible
        Try
            _backgroundWorker_Save = New BackgroundWorker
            Dim DepartmentExist As Boolean = False

            If Not _departmentList Is Nothing Then
                If _departmentList.Where(Function(x) x.DepartmentCode = textboxCode.Text).Count > 0 Then
                    DepartmentExist = True
                End If
            End If

            If DepartmentExist Then
                'edit
                _backgroundWorker_Save.RunWorkerAsync("edit")
                _departmentDetail.ResetDirtyBit()
            Else
                'new
                _departmentDetail = New Department
                With _departmentDetail
                    .DepartmentCode = If(textboxCode.Text.Length = 0, Nothing, textboxCode.Text)
                    .DepartmentName = If(textboxName.Text.Length = 0, Nothing, textboxName.Text)
                    .DepartmentDesc = If(textboxDescription.Text.Length = 0, Nothing, textboxDescription.Text)
                End With

                _backgroundWorker_Save.RunWorkerAsync("new")

                If Not _departmentList Is Nothing Then
                    'update list
                    _departmentList.Add(_departmentDetail)
                    sortData()
                    Dim ctr As Integer = 0
                    For Each item In _departmentList
                        If item.DepartmentId = _departmentDetail.DepartmentId Then
                            Exit For
                        End If
                        ctr += 1
                    Next
                    listBoxDepartments.SelectedIndex = ctr
                End If
            End If
            _departmentDetail.ResetDirtyBit()
            SetWindowProperties(_departmentDetail.IsDirty)

            _backgroundWorker_Save.Dispose()
        Catch faultEx As FaultException
            MessageBox.Show(faultEx.Message, "Error Saving Department Details", MessageBoxButton.OK, MessageBoxImage.[Error])
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error Saving Department Details", MessageBoxButton.OK, MessageBoxImage.[Error])
        End Try
        busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Collapsed
    End Sub

    Sub sortData()
        Dim ied As IEnumerable(Of Department) = From d In _departmentList Order By d.DepartmentName
        For Each i In ied
            _departmentList.Remove(i)
            _departmentList.Add(i)
        Next
    End Sub

    Private Sub LoadSelectedDepartment()
        If listBoxDepartments.SelectedIndex >= 0 Then
            _departmentDetail = listBoxDepartments.SelectedItem
            _departmentDetail.ResetDirtyBit()
            HookupChangeEventHandler(_departmentDetail)
            mainOverlay.Visibility = Visibility.Collapsed
            Me.Title = textboxCode.Text
            _departmentDetail.BeginEdit()
            Me.DataContext = _departmentDetail
        Else
            _departmentDetail = Nothing
            Me.Title = "Department"
            mainOverlay.Visibility = Visibility.Visible
        End If
        If Not _departmentDetail Is Nothing Then
            SetWindowProperties(_departmentDetail.IsDirty)
        Else
            SetWindowProperties(False)
        End If
    End Sub

    Private Sub HookupChangeEventHandler(departmentDetail As Department)
        ' Add a PropertyChanged event handler for 
        ' the specified Customer instance:
        AddHandler _departmentDetail.PropertyChanged, _
            AddressOf HandlePropertyChanged
    End Sub

    Private Sub HandlePropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs)
        If _departmentDetail.IsDirty Then
            SetWindowProperties(_departmentDetail.IsDirty)
        End If
    End Sub

    Public Function FilterUserTable(ByVal t As Object) As Boolean
        Dim _department As Department
        _department = t
        Return _department.DepartmentName.ToUpper.Contains(searchBox.Text.ToUpper)
    End Function

    Sub ClearAllControls()
        HelperClass.ClearCheckBox(DepartmentWindow)
        HelperClass.ClearComboBox(DepartmentWindow)
        HelperClass.ClearPasswordBox(DepartmentWindow)
        HelperClass.ClearTextBox(DepartmentWindow)
        Me.Title = "Department"
        _departmentDetail.ResetDirtyBit()
        SetWindowProperties(_departmentDetail.IsDirty)
    End Sub

    Private Sub TextBox_Error(sender As Object, e As ValidationErrorEventArgs)
        If e.Action = ValidationErrorEventAction.Added Then
            DirectCast(sender, Control).ToolTip = e.[Error].ErrorContent.ToString()
        Else
            DirectCast(sender, Control).ToolTip = ""
        End If
    End Sub
#End Region

#Region "User Control Events"

    Private Sub uc_OKButtonClicked(ByVal sender As Object, ByVal e As RoutedEventArgs) _
        Handles ucNewItem.OkButtonClicked
        ucNewItem.busyAnimationNewUser_visibility = Windows.Visibility.Visible
        _backgroundWorker_CheckExisting = New BackgroundWorker
        _backgroundWorker_CheckExisting.RunWorkerAsync(ucNewItem.TextBoxNewUser.Text)
        _backgroundWorker_CheckExisting.Dispose()
    End Sub

    Private Sub uc_CancelButtonClicked(ByVal sender As Object, ByVal e As RoutedEventArgs) _
        Handles ucNewItem.CancelButtonClicked
        NewItemCanvas.Visibility = Windows.Visibility.Collapsed
    End Sub

#End Region

End Class
